package com.gopay.bis.payease.ebank.operation;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.builder.ToStringBuilder;

import com.capinfo.crypt.Md5;
import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.payease.ebank.operation.parse.SAXParser;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.payease.ebank.PayEaseMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.HttpsTransport;

/**
 * 首信查询
 * 
 * @UnionPayCerthelperQuery.java
 * @author liuzp
 */
public class PayEaseCertHelperQuery {
	
	private HttpsTransport httpsTransport;

	public PayEaseMessage query(BaseMessage message)  throws GopayException{
		try {
			Map<String, String> param = new HashMap<String, String>();
			PayEaseMessage msg = (PayEaseMessage)message;
			param.put("v_mid", msg.getVmid());
			param.put("v_oid", msg.getVid());
			Md5 md5 = new Md5("");
			md5.hmac_Md5(msg.getPlainMessage(), msg.getPrivateKeyPath()); // 参数拼串
			byte[] b = md5.getDigest();
			String digestString = md5.stringify(b);
			param.put("v_mac", digestString); // 密钥
			httpsTransport.setUrl(message.getQueryUrl());  //
			BankLogUtils.printB2CQuerySendLog(message, ToStringBuilder.reflectionToString(param));
			String retStr = (String) httpsTransport.submit(param);
			PayEaseMessage retMsg = parse(retStr);
			BankLogUtils.printB2CQueryBlackLog(retMsg, ToStringBuilder.reflectionToString(retMsg));
			return retMsg;
		} catch (Exception e) {
			BankLogUtils.printB2CQueryExceptionLog(message, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
		}
	}

	/**
	 * 首信查询后报文转换
	 * 
	 * @param Object messageData
	 * @return UnionPayMesse
	 */
	private PayEaseMessage parse(String xmlMsg)  throws GopayException{
		PayEaseMessage msg = new PayEaseMessage();
		try{
			String vpmode = SAXParser.SAXParseNodeValue(xmlMsg, "pmode");
			String vpstatus = SAXParser.SAXParseNodeValue(xmlMsg, "pstatus");
			String vpstring = SAXParser.SAXParseNodeValue(xmlMsg, "pstring");
			String vpamount = SAXParser.SAXParseNodeValue(xmlMsg, "amount");
			String vmd5money = SAXParser.SAXParseNodeValue(xmlMsg, "md5info");
			String vsign = SAXParser.SAXParseNodeValue(xmlMsg, "vsign");
			msg.setVpmode(vpmode);
			msg.setVpstatus(vpstatus);//msg.setVpstatus("1");//
			msg.setVpstring(vpstring);
			msg.setVamount(vpamount);
			msg.setVmd5money(vmd5money);
			msg.setVsign(vsign);
			//打日志用
			msg.setOutStlmCd("PAYEASE");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return msg;
	}

	public void setHttpsTransport(HttpsTransport httpsTransport) {
		this.httpsTransport = httpsTransport;
	}
}
